package com.bkfm.framework.core.ctrl;

import java.io.File;
import java.io.FileInputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.yak.common.digest.DESUtils;
import org.yak.core.web.BaseController;

import com.bkfm.framework.core.api.service.IBkfmTableMetaServer;
import com.bkfm.framework.core.entity.BkfmTableMetaData;

/**
 * 
 * 工具
 * @平台：统一开发平台
 * @文件名称：BkfmUtilCtrl.java
 * @文件描述：
 * @author xuqiang
 * @日期：2018年9月10日上午11:02:39
 *
 */
@Controller
@RequestMapping("/bkfm/common/**")
public class BkfmUtilCtrl extends BaseController<BkfmTableMetaData>{

	@Resource
	private IBkfmTableMetaServer bkfmTableMetaService;
	
	/**
	 * excel文件下载,直接请求下载附件的绝对地址
	 * @param model
	 * @return
	 */
	@RequestMapping("/download")
	public void download(String downloadInfo,HttpServletResponse response,Model model){
		try {
			String filePath = DESUtils.decryption(downloadInfo, DESUtils.SECRETKEY);
	        // 读到流中
			File file = new File(filePath);
			String fileName = file.getName();
	        FileInputStream inStream = new FileInputStream(file);// 文件的存放路径
	        String agent = request.getHeader("USER-AGENT");
	        String downLoadName = null;
	        if (null != agent && -1 != agent.indexOf("MSIE")){
	        	//IE
	          downLoadName = java.net.URLEncoder.encode(fileName, "UTF-8");
	        }else if (null != agent && -1 != agent.indexOf("Mozilla")){
	        	//Firefox
	          downLoadName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");
	        }else{
	          downLoadName = java.net.URLEncoder.encode(fileName, "UTF-8");
	        }
	        // 设置输出的格式
	        response.setHeader("Content-disposition", "attachment;filename="+ downLoadName );
	        if(filePath.toUpperCase().endsWith("XLS")){
	        	response.setContentType("application/vnd.ms-excel;charset=UTF-8");
	        }else if(filePath.toUpperCase().endsWith("PDF")){
	        	response.setContentType("application/pdf;charset=UTF-8");
	        }else if(filePath.toUpperCase().endsWith("ZIP")){
	        	response.setContentType("application/zip;charset=UTF-8");
	        }
	        // 循环取出流中的数据
	        byte[] b = new byte[1024];
	        int len;
	        while ((len = inStream.read(b)) > 0) {
	            response.getOutputStream().write(b, 0, len);
	        }
	        inStream.close();
		}catch(Exception e) {
			logger.error("下载文件异常",e);
		}
	}
}
